package com.ttdevs.ttrss.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.mcsoxford.rss.RSSFeed;
import org.mcsoxford.rss.RSSItem;
import org.mcsoxford.rss.RSSReader;
import org.mcsoxford.rss.RSSReaderException;

public class URLConn implements IConnection {

	@Override
	public InputStream getResult(String urlStr) throws IOException {
		URL url = new URL(urlStr);
		URLConnection urlConn = url.openConnection();
		urlConn.setConnectTimeout(30 * 1000);
		return urlConn.getInputStream();
	}

	@Override
	public void startRequest(final String link,
			final OnNetworkRespListener listener) {
		if (listener == null) {
			return;
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					URL url = new URL(link);
					URLConnection urlConn = url.openConnection();
					urlConn.setConnectTimeout(30 * 1000);
					InputStream is = urlConn.getInputStream();
					listener.onNetworkResp(true, is);
				} catch (Exception e) {
					e.printStackTrace();
					listener.onNetworkResp(false, null);
				}
			}
		}).start();
	}

	@Override
	public void sendRequest(final String link, final OnResponseListener listener) {
		if (listener == null) {
			return;
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					RSSReader reader = new RSSReader();
					RSSFeed feed = reader.load(link);
					List<RSSItem> list = feed.getItems();
					
					listener.oResponse(list != null, list);
					
					reader.close();
				} catch (RSSReaderException e) {
					e.printStackTrace();
					listener.oResponse(false, null);
				}
			}
		}).start();
	}
}
